var express = require('express');
var router = express.Router();
var axios = require('axios')
var jwt = require('jsonwebtoken')
var fs = require('fs')
var path = require('path')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/auth', async (req, res) => {
  const appid = 'wxeb8c70d2f9b9d1d3'
  const secret = 'b1f50332048af1896126a8f27edec93a'
  const js_code = req.body.code

  let result = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
    params: {
      appid,
      secret,
      js_code,
      grant_type: 'authorization_code'
    }
  })

  const privateKey = fs.readFileSync(path.resolve(__dirname, '../cert/rsa_private_key.pem'), 'utf-8')
  const token = jwt.sign(result.data, privateKey, { algorithm: 'RS256' })

  res.send(token)
})

router.post('/isAuth', async (req, res) => {
  const publicKey = fs.readFileSync(path.resolve(__dirname, '../cert/rsa_public_key.pem'))
  jwt.verify(req.body.token, publicKey, function(err, decoded) {
    if(decoded) {
      res.json({
        ret: true,
        message: 'succ'
      })
    } else {
      res.json({
        ret: false,
        message: 'fail'
      })
    }
  })
})

module.exports = router;
